package jwtutil

import (
	"github.com/RaymondCode/simple-demo/config"
	"github.com/dgrijalva/jwt-go"
	"time"
)

var mySigningKey []byte

func InitJWT() {
	mySigningKey = []byte(config.Config.Jwt.SecretKey)
}

func CreateJWT(id int) (string, error) {
	// 加密用户id
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"id":  id,
		"exp": time.Now().Unix() + int64(config.Config.Jwt.ExpireTime),
	})
	// 使用密钥再次加密token
	tokenString, err := token.SignedString(mySigningKey)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

func ParseJWT(token string) (int, error) {
	tokenOriginal, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		return mySigningKey, nil
	})
	if err != nil {
		return 0, err
	}
	id := tokenOriginal.Claims.(jwt.MapClaims)["id"].(float64)
	return int(id), nil
}
